import json
from django import http
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.shortcuts import render_to_response, HttpResponseRedirect, get_object_or_404, HttpResponse
from django.template import RequestContext
import Apps.data.RSSReader
from django.contrib.auth.models import User
from Apps.data.models import article, comment
import datetime
from Apps.data.form import CommentForm
from django.utils.dateparse import parse_datetime
import django.utils.timezone

@csrf_exempt
def addComment(request):
    if request.method == 'POST':
        #form = CommentForm(request.POST)
        ## Handle AJAX  ##
        if request.is_ajax():
            if (request.POST.get("content", "") and request.POST.get('userid', '') and request.POST.get('articleid', '')):
                cont = request.POST.get('content', '')
                userid = request.POST.get('userid', '')
                articleid = request.POST.get('articleid', '')

                user = User.objects.get(id=userid)
                art = article.objects.get(id=articleid)
                # Get a list of Categories to return

                comtSave = comment(content=cont, userID=user, artID = art)
                comtSave.save()
                # Create a dictionary for our response data
                data = {
                    'error': False,
                    # Django model instances are not serializable
                    'comments': cont,
                    'commentID': comtSave.id,
                    'userName': user.username,
                    'userID': user.id,
                    'postOnDate': str(comtSave.postOnDate),
                    }
            else:
                # Form was not valid, get the errors from the form and
                # create a dictionary for our error response.
                data = {
                    'error': True,
                    }
                # encode the data as a json object and return it
            return http.HttpResponse(json.dumps(data), mimetype="application/json")

        ## Old Form Handler Logic ##
        """if form.is_valid():
            form.save()
            return http.HttpResponseRedirect(request.path)
        """
    data = {
        'error': True,
        }
    # encode the data as a json object and return it
    return http.HttpResponse(json.dumps(data), mimetype="application/json")

@csrf_exempt
def ajaxTest(request):
    e = ""
    post_text = "1234test"
    #try:
    #    post_text = request.POST.get('post_data', '')
    #except Exception as e:
    #    er = e
    data = {
        'response_text': post_text
    }
    return HttpResponse(json.dumps(data))
    #return HttpResponseRedirect('/rss/')

@csrf_exempt
def addLike(request):
    if request.method == 'POST':
        if request.is_ajax():
            if request.POST.get("commentID", ""):
                try:
                    user = request.user
                    commentID = request.POST.get("commentID", "")

                    comm = comment.objects.get(id=commentID)
                    likeUser = comment.objects.get(id=commentID).likeUser

                    comm.likeUser.add(user)

                    data = {
                        'error': False,
                        'voted': comm.likeUser.count(),
                        }
                    return http.HttpResponse(json.dumps(data), mimetype="application/json")
                except :
                    #donothing
                    data = {
                        'error': True,
                    }
                    return http.HttpResponse(json.dumps(data), mimetype="application/json")
            else:
                data = {
                    'error': True,
                }
                return http.HttpResponse(json.dumps(data), mimetype="application/json")
    data = {
        'error': True,
    }
    return http.HttpResponse(json.dumps(data), mimetype="application/json")
"""
    Save data from dantri.com.vn
"""
def saveVnxpress(catelog ,items, source, linkRep, type):
    for item in items:
        try:
            tit = item.title
            sour = source
            desc = item.description
            links = str(item.link).replace(linkRep, '')
            links = links.replace('/', '_')
            links = links.replace('-', '_')
            links = links + '/'
            links = "/"+catelog+"/"+links
            des1 = str(desc).find('<a href="')
            des2 = str(desc).find('">')
            replaceStr = desc[des1+9:des2]
            desc = str(desc).replace(replaceStr , links)
            aType = type
            pubDatetime = item.pubDate
            #index1 = str(pubDatetime).index(',')
            index2 = str(pubDatetime).index('GMT')
            pubDatetime = pubDatetime[0:index2-1]
            date = datetime.datetime.strptime(pubDatetime, "%a, %d %b %Y %H:%M:%S")
            #django.utils.timezone.make_aware(date, "America/Chicago")
            htmlString = Apps.data.RSSReader.getDetails(item.link)
            top = htmlString.index('<div class="content"');
            if (top > 0):
                content1 = htmlString[top + 21: len(htmlString) - top - 22]
            bot = content1.rindex('class="tag-parent"');
            content = content1[0:bot-5]

            content = content.replace('http://vnexpress.net','')
            content = content.replace('"/gl/','')
            content = content.replace('/Files', 'http://vnexpress.net/Files')
            content = content.replace('/Library', 'http://vnexpress.net/Library')
            content = content.replace('/Images', 'http://vnexpress.net/Images')
            content = content.replace('/Service', 'http://vnexpress.net/Service')

            img = ""
            img1 = ""
            try:
                imgIndex1 = content.find('<IMG')
                if (int(imgIndex1) != -1):
                    img = content[imgIndex1:]
                    imgIndex2 = img.find('">')
                    img1 = img[0:imgIndex2+2]
            except :
                img1 = ""

            p = article(title=tit,link= links, source=sour, description=desc, category = catelog, typeOf=aType, image=img1, pubDate=date, contents=content)
            p.save()

        except Exception as e:
            # Continue
            ex = str(e)
            continue

"""
    Add article about sport
"""
def addArtSport(request):
    url1 = 'http://vnexpress.net/rss/gl/the-thao.rss'
    url2 = 'http://dantri.com.vn/the-thao.rss'
    url3 = 'http://www.24h.com.vn/upload/rss/thethao.rss'

    source1 = 'vnexpress.net'
    source2 = 'dantri.com.vn'
    source3 = 'www.24h.com.vn'

    rss_reader1 = Apps.data.RSSReader.RSSReader(url1)
    rss_reader2 = Apps.data.RSSReader.RSSReader(url2)
    rss_reader3 = Apps.data.RSSReader.RSSReader(url3)

    rss_items1 = rss_reader1.GetItems()
    rss_items2 = rss_reader2.GetItems()
    rss_items3 = rss_reader3.GetItems()
    rss = rss_items1
    for item in rss_items1:
        try:
            tit = item.title
            sour = 'vnexpress.net'
            desc = item.description
            links = str(item.link).replace('http://thethao.vnexpress.net/tin-tuc', '')
            links = links.replace('/', '_')
            links = links.replace('-', '_')
            links = links.replace('.html', '/')
            links = "/sport/"+links
            des1 = str(desc).find('<a href="')
            des2 = str(desc).find('.html')
            linksDes = "javascript:void(0)\" name=\""+links+"\" class=\"modal"
            replaceStr = desc[des1+9:des2+5]
            desc = str(desc).replace(replaceStr , linksDes)
            aType = 'other'
            if (str(item.link).find('champions-league') != -1):
                aType = 'champions-league'
            elif (str(item.link).find('giai-ngoai-hang-anh') != -1):
                aType = 'giai-ngoai-hang-anh'
            elif (str(item.link).find('la-liga') != -1):
                aType = 'la-liga'
            else:
                aType = 'other'
            cate = 'sport'
            pubDatetime = item.pubDate
            #index1 = str(pubDatetime).index(',')
            index2 = str(pubDatetime).index('+')
            pubDatetime = pubDatetime[0:index2-1]
            date = datetime.datetime.strptime(pubDatetime, "%a, %d %b %Y %H:%M:%S")
            #django.utils.timezone.make_aware(date, "America/Chicago")
            htmlString = Apps.data.RSSReader.getDetails(item.link)
            top = htmlString.index('<div class="main_content_detail"');
            if (top > 0):
                content1 = htmlString[top + 33: len(htmlString) - top - 34]
            bot = content1.rindex('class="share_bar w160 right"');
            content = content1[0:bot-5]

            content = content.replace('http://vnexpress.net','')
            content = content.replace('"/gl/','')
            content = content.replace('/Files', 'http://vnexpress.net/Files')
            content = content.replace('/Library', 'http://vnexpress.net/Library')
            content = content.replace('/Images', 'http://vnexpress.net/Images')
            content = content.replace('/Service', 'http://vnexpress.net/Service')

            img = ""
            img1 = ""
            try:
                imgIndex1 = content.find('<img')
                if (int(imgIndex1) != -1):
                    img = content[imgIndex1:]
                    imgIndex2 = img.find('">')
                    img1 = img[0:imgIndex2+2]
            except :
                img1 = ""

            p = article(title=tit,link= links, source=sour, description=desc, category = cate, typeOf=aType, image=img1, pubDate=date, contents=content)
            p.save()

        except Exception as e:
            # Continue
            ex = str(e)
            continue

    return render_to_response('registration/thanks.html', {'rss_items': rss}, context_instance=RequestContext(request))

"""
    Add article about entertainment
"""
def saveDataEnt(catelog ,items, source, linkRep, type):
    ex = ""
    for item in items:
        try:
            tit = item.title
            sour = source
            desc = item.description
            links = str(item.link).replace(linkRep, '')
            links = links.replace(' ', '')
            links = links.replace('/', '_')
            links = links.replace('-', '_')
            links = links.replace('.htm', '/')
            links = "/"+ catelog +"/"+links
            des1 = str(desc).find("<a href='")
            des2 = str(desc).find('.htm')
            replaceStr = desc[des1+13:des2+4]
            desc = str(desc).replace(replaceStr , links)
            aType = type

            pubDatetime = item.pubDate
            #index1 = str(pubDatetime).index(',')
            #index2 = str(pubDatetime).index('+')
            #pubDatetime = pubDatetime[0:index2-1]
            date = datetime.datetime.strptime(pubDatetime, "%m/%d/%Y %H:%M:%S %p")
            #django.utils.timezone.make_aware(date, "America/Chicago")
            htmlString = Apps.data.RSSReader.getDetails(item.link)
            top = htmlString.index('<div id="ctl00_IDContent_ctl00_divContent"');
            if (top > 0):
                content1 = htmlString[top + 43: len(htmlString) - top - 34]
            bot = content1.rindex('id="div_tamlongnhanai"');
            content = content1[0:bot+29]


            img = ""
            img1 = ""
            try:
                imgIndex1 = content.find('<IMG')
                if (int(imgIndex1) != -1):
                    img = content[imgIndex1:]
                    imgIndex2 = img.find('">')
                    img1 = img[0:imgIndex2+2]
            except :
                img1 = ""

            p = article(title=tit,link= links, source=sour, description=desc, category = catelog, typeOf=aType, image=img1, pubDate=date, contents=content)
            p.save()

        except Exception as e:
            # Continue
            ex = str(e)
            continue
    return ex
#########################################################################
def addArtEnt(request):
    urlVanhoa = 'http://dantri.com.vn/van-hoa.rss'
    urlAmnhac = 'http://dantri.com.vn/amnhac.rss'
    urlThoitrang = 'http://dantri.com.vn/thoitrang.rss'
    urlPhim = 'http://dantri.com.vn/phim.rss'
    urlOther = 'http://dantri.com.vn/anchoi.rss'

    rssVanhoa = Apps.data.RSSReader.RSSReader(urlVanhoa)
    rssAmnhac = Apps.data.RSSReader.RSSReader(urlAmnhac)
    rssThoitrang = Apps.data.RSSReader.RSSReader(urlThoitrang)
    rssPhim = Apps.data.RSSReader.RSSReader(urlPhim)
    rssOther = Apps.data.RSSReader.RSSReader(urlOther)

    itemsVanhoa = rssVanhoa.GetItems()
    itemsAmnhac = rssAmnhac.GetItems()
    itemsThoitrang = rssThoitrang.GetItems()
    itemsPhim = rssPhim.GetItems()
    itemsOther = rssOther.GetItems()
    t = itemsPhim

    saveDataEnt('entertainment', itemsPhim, 'dantri.com.vn', 'http://dantri.com.vn', 'other')
    saveDataEnt('entertainment', itemsVanhoa, 'dantri.com.vn', 'http://dantri.com.vn/', 'vanhoa')
    saveDataEnt('entertainment', itemsAmnhac, 'dantri.com.vn', 'http://dantri.com.vn/', 'amnhac')
    saveDataEnt('entertainment', itemsThoitrang, 'dantri.com.vn', 'http://dantri.com.vn/', 'thoitrang')
    saveDataEnt('entertainment', itemsOther, 'dantri.com.vn', 'http://dantri.com.vn', 'other')

    return render_to_response('registration/thanks.html', {'rss_items': t}, context_instance=RequestContext(request))
################################################################################################################################
### Add data about technology
################################################################################################################################
def addArtTech(request):
    urlVitinh = 'http://dantri.com.vn/vitinh.rss'
    urlDienthoai = 'http://dantri.com.vn/dienthoai.rss'
    urlThuthuat = 'http://dantri.com.vn/thuthuat.rss'
    urlVnxpress = 'http://vnexpress.net/rss/gl/vi-tinh.rss'

    rssVitinh = Apps.data.RSSReader.RSSReader(urlVitinh)
    rssDienthoai = Apps.data.RSSReader.RSSReader(urlDienthoai)
    rssThuthuat = Apps.data.RSSReader.RSSReader(urlThuthuat)
    rssVnxpress = Apps.data.RSSReader.RSSReader(urlVnxpress)

    itemsVitinh = rssVitinh.GetItems()
    itemsDienthoai = rssDienthoai.GetItems()
    itemsThuthuat = rssThuthuat.GetItems()
    itemsVnxpress = rssVnxpress.GetItems();

    saveDataEnt('technology', itemsVitinh, 'dantri.com.vn', 'http://dantri.com.vn', 'dantri.com.vn')
    saveDataEnt('technology', itemsDienthoai, 'dantri.com.vn', 'http://dantri.com.vn', 'dantri.com.vn')
    saveDataEnt('technology', itemsThuthuat, 'dantri.com.vn', 'http://dantri.com.vn', 'dantri.com.vn')
    saveVnxpress('technology', itemsVnxpress, 'vnxpress.net', 'http://vnexpress.net/gl/vi-tinh', 'vnxpress.net')

    return render_to_response('registration/thanks.html', context_instance=RequestContext(request))

##################################################
## Add article about law
##################################################
def saveVnxpress1(catelog ,items, source, linkRep, type):
    for item in items:
        try:
            tit = item.title
            sour = source
            desc = item.description
            links = str(item.link).replace(linkRep, '')
            links = links.replace('/', '_')
            links = links.replace('-', '_')
            links = links + '/'
            links = "/"+catelog+"/"+links
            linksDes = "javascript:void(0)\" name=\""+links+"\" class=\"modal"
            des1 = str(desc).find('<a href="')
            des2 = str(desc).find('">')
            replaceStr = desc[des1+9:des2]
            desc = str(desc).replace(replaceStr , linksDes)
            aType = type
            pubDatetime = item.pubDate
            #index1 = str(pubDatetime).index(',')
            index2 = str(pubDatetime).index('GMT')
            pubDatetime = pubDatetime[0:index2-1]
            date = datetime.datetime.strptime(pubDatetime, "%a, %d %b %Y %H:%M:%S")
            #django.utils.timezone.make_aware(date, "America/Chicago")
            htmlString = Apps.data.RSSReader.getDetails(item.link)
            top = htmlString.index('<div class="content"');
            if (top > 0):
                content1 = htmlString[top + 21: len(htmlString) - top - 22]
            bot = content1.rindex('class="tag-parent"');
            content = content1[0:bot-5]

            content = content.replace('http://vnexpress.net','')
            content = content.replace('"/gl/','')
            content = content.replace('/Files', 'http://vnexpress.net/Files')
            content = content.replace('/Library', 'http://vnexpress.net/Library')
            content = content.replace('/Images', 'http://vnexpress.net/Images')
            content = content.replace('/Service', 'http://vnexpress.net/Service')

            img = ""
            img1 = ""
            try:
                imgIndex1 = content.find('<IMG')
                if (int(imgIndex1) != -1):
                    img = content[imgIndex1:]
                    imgIndex2 = img.find('>')
                    img1 = img[0:imgIndex2+1]
            except :
                img1 = ""

            p = article(title=tit,link= links, source=sour, description=desc, category = catelog, typeOf=aType, image=img1, pubDate=date, contents=content)
            p.save()

        except Exception as e:
            # Continue
            ex = str(e)
            continue

def addDataLaw(request):
    urlLuat = 'http://vnexpress.net/rss/gl/phap-luat.rss'
    urlDoisong = 'http://vnexpress.net/rss/gl/doi-song.rss'
    urlKinhdoanh = 'http://vnexpress.net/rss/gl/kinh-doanh.rss'
    urlXahoi = 'http://vnexpress.net/rss/gl/xa-hoi.rss'
    urlThegioi = 'http://vnexpress.net/rss/gl/the-gioi.rss'

    rssLuat = Apps.data.RSSReader.RSSReader(urlLuat)
    rssDoisong = Apps.data.RSSReader.RSSReader(urlDoisong)
    rssKinhdoanh = Apps.data.RSSReader.RSSReader(urlKinhdoanh)
    rssXahoi = Apps.data.RSSReader.RSSReader(urlXahoi)
    rssThegioi = Apps.data.RSSReader.RSSReader(urlThegioi)

    itemsLuat = rssLuat.GetItems()
    itemsDoisong = rssDoisong.GetItems()
    itemsKinhdoanh = rssKinhdoanh.GetItems()
    itemsXahoi = rssXahoi.GetItems()
    itemsThegioi = rssThegioi.GetItems()

    saveVnxpress1('total', itemsLuat, 'vnxpress.net', 'http://vnexpress.net/gl/phap-luat', 'vnxpress.net')
    saveVnxpress1('total', itemsDoisong, 'vnxpress.net', 'http://vnexpress.net/gl/doi-song', 'vnxpress.net')
    saveVnxpress1('total', itemsKinhdoanh, 'vnxpress.net', 'http://vnexpress.net/gl/kinh-doanh', 'vnxpress.net')
    saveVnxpress1('total', itemsXahoi, 'vnxpress.net', 'http://vnexpress.net/gl/xa-hoi', 'vnxpress.net')
    saveVnxpress1('total', itemsThegioi, 'vnxpress.net', 'http://vnexpress.net/gl/the-gioi', 'vnxpress.net')

    return render_to_response('registration/thanks.html', context_instance=RequestContext(request))

################################################################################################################################
def detailsSport(request, name):
    if request.method == 'POST':
        #form = CommentForm(request.POST)
        ## Handle AJAX  ##
        if request.is_ajax():
            if (request.POST.get("content", "") and request.POST.get('userid', '') and request.POST.get('articleid', '')):
                cont = request.POST.get('content', '')
                userid = request.POST.get('userid', '')
                articleid = request.POST.get('articleid', '')

                user = User.objects.get(id=userid)
                art = article.objects.get(id=articleid)
                # Get a list of Categories to return
                comtSave = comment(content=cont, userID=user, artID = art)
                comtSave.save()
                # Create a dictionary for our response data
                data = {
                    'error': False,
                    # Django model instances are not serializable
                    'comments': cont,
                    'commentID': comtSave.id,
                    }
            else:
                # Form was not valid, get the errors from the form and
                # create a dictionary for our error response.
                data = {
                    'error': True,
                }
                # encode the data as a json object and return it
            return http.HttpResponse(json.dumps(data), mimetype="application/json")

        ## Old Form Handler Logic ##
        """if form.is_valid():
            form.save()
            return http.HttpResponseRedirect(request.path)
        """

    det = article.objects.get(link="/sport/"+name+"/")
    comments = comment.objects.filter(artID = det)
    s=request.GET.get("state")

    s=request.GET.get("state")
    new=article.objects.filter(category="sport")
    size=new.count();
    new=new[size-4:size]
    new=new.reverse();
    new1=new[0]
    new2=new[1]
    new3=new[2]
    new4=new[3]
    div="</div>"
    context = RequestContext(request, {'inra': det, 'comments': comments,"div":div,"s":s,"n1":new1,"n2":new2,"n3":new3,"n4":new4,})
    if s=="newtab":
        return render_to_response('homepage/details1.html', context)
    return render_to_response('homepage/details.html', context)

def detailsEnter(request, name):
    e = ""
    try:
        det = article.objects.get(link="/entertainment/"+name+"/")
        comments = comment.objects.filter(artID = det)
    except Exception as e:
        er = e
        det = None
        comments = None
    s=request.GET.get("state")
    new=article.objects.filter(category="entertainment")
    size=new.count();
    new=new[size-4:size]
    new=new.reverse();
    new1=new[0]
    new2=new[1]
    new3=new[2]
    new4=new[3]
    if s=="newtab":
        return render_to_response('homepage/details1.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))
    return render_to_response('homepage/details.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))

def detailTech(request, name):
    e = ""
    try:
        det = article.objects.get(link="/technology/"+name+"/")
        comments = comment.objects.filter(artID = det)
    except  Exception as e:
        er = e
        det = None
        comments = None
    s=request.GET.get("state")
    new=article.objects.filter(category="technology")
    size=new.count();
    new=new[size-4:size]
    new=new.reverse();
    new1=new[0]
    new2=new[1]
    new3=new[2]
    new4=new[3]
    if s=="newtab":
        return render_to_response('homepage/details1.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))
    return render_to_response('homepage/details.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))
def detailTotal(request, name):
    e = ""
    try:
        det = article.objects.get(link="/total/"+name+"/")
        comments = comment.objects.filter(artID = det)
    except  Exception as e:
        er = e
        det = None
        comments = None
    s=request.GET.get("state")

    new=article.objects.filter(category="total")
    size=new.count();
    new=new[size-4:size]
    new=new.reverse();
    new1=new[0]
    new2=new[1]
    new3=new[2]
    new4=new[3]
    if s=="newtab":
        return render_to_response('homepage/details1.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))
    return render_to_response('homepage/details.html', {'e': e, 'inra': det, 'path': request.path, 'comments': comments,"n1":new1,"n2":new2,"n3":new3,"n4":new4}, context_instance=RequestContext(request))
def detTest(request):
    det = article.objects.get(link="/entertainment/c730_s730_599979_ky_niem_100_nam_ngay_sinh_thi_si_ho_han_voi_truong_ca_han_mac_tu/")
    return render_to_response('homepage/details.html', {'inra': det}, context_instance=RequestContext(request))
